package ThreadConstruction;

import java.util.ArrayList;
import java.util.List;

public class good {

    public static void main(String[] args) {

        // 定义一个集合类，模拟存储生产的商品
        List<Object> good = new ArrayList<>();
        // 记录线程执行前统一的开始时间
        Long begin = System.currentTimeMillis();

        // 创建一个生产者线程，用于生产并存入商品集合
        Thread create = new Thread(()->{
           int num = 0;
           while (System.currentTimeMillis() - begin <= 100){
               synchronized (good){
                   if (good.size()>0){
                       try{
                           good.wait();
                       }catch(Exception e){
                           e.printStackTrace();
                       }
                   } else {
                       good.add("商品"+num++);
                       System.out.println("生产商品"+num);
                   }
               }
           }
        },"生产者");

        // 创建一个消费者线程，用于消费并将商品从商品集合中删除
        Thread customer = new Thread(()->{
            int num = 0;
            while (System.currentTimeMillis() - begin <=100){
                synchronized (good){
                    if (good.size()<=0){
                        try{
                            good.notify();
                        }catch(Exception e){
                            e.printStackTrace();
                        }
                    }else {
                        good.remove("商品" + num++);
                        System.out.println("消费商品" + num);
                        System.out.println(good.size());
                    }
                }
            }
        },"消费者");

        // 启动线程
        create.start();
        customer.start();



    }

}
